package com.woniuxy.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.entity.User;
import com.woniuxy.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 马宇航
 * @Todo: 局部过滤器，暂时用不上
 * @DateTime: 25/08/06/星期三 11:50
 * @Component: 成都蜗牛学苑
 **/
@Component
public class ConsumerAuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate redisTemplate;
    private final List<String> whiteList = Arrays.asList("/auth/login", "/auth/register");
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //先判断是不是白名单中的请求
        String path = exchange.getRequest().getPath().toString();
        if (whiteList.contains(path)) {
            //如果是白名单直接放行，暂时不考虑正则校验
            return chain.filter(exchange);
        }
//      1.从请求头中获取refreshToken和jwt（jwt存活时间不能太长）
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        String refreshToken = exchange.getRequest().getHeaders().getFirst("refreshAuthorization");
        //2.判断token是否为空,但是要排除白名单，某些请求不需要认证
        if (token == null || token.isEmpty()) {
            return unauthMessage(exchange);
        }else{
            //先判断token有没有过期。
            JWTUtils.TokenStatusEnum verify = JWTUtils.verify(token);
            //jwt过期，但是refreshToken还没有
            if (verify.equals(JWTUtils.TokenStatusEnum.TOKEN_EXPIRE)){
                //去redis取值 （2种情况，刷新token没了，或者可以查询到）
                return checkRefreshToken(exchange,chain, refreshToken);
            }else if(verify.equals(JWTUtils.TokenStatusEnum.TOKEN_ERROR)){
                //3.如果为空，返回未授权错误 401未认证响应码
                return unauthMessage(exchange);
            }else {
                //认证通过就放行，token没过期,延迟刷新token再redis中的时间
                redisTemplate.expire(refreshToken,JWTUtils.REFRESH_TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
                return chain.filter(exchange);
            }
        }
    }

    private Mono<Void> unauthMessage(ServerWebExchange exchange) {
        //3.如果为空，返回未授权错误 401未认证响应码
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //99.把ResponseEntiy响应回去
        byte[] bytes = null;
        try {
            bytes = new ObjectMapper().writeValueAsBytes(new ResponseEntity("登录过期，请重新登录"));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        //数据缓存
        DataBuffer wrap = exchange.getResponse().bufferFactory().wrap(bytes);
        //前端通过响应嘛，直接跳转到对应的登录页面,不放行要响应数据回去
        return exchange.getResponse().writeWith(Mono.just(wrap));
    }

    public Mono<Void> checkRefreshToken(ServerWebExchange exchange,GatewayFilterChain chain,String refreshToken){
        //直接取值
        Map<String,Object> userInfo = redisTemplate.opsForHash().entries("refreshToken");
        if (userInfo.isEmpty()){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }else {
            //非空，此时是token过期
            String token = JWTUtils.createToken(((User) userInfo.get("user")).getUsername());
            //新token存入redis中
            userInfo.put("token",token);
            redisTemplate.opsForHash().putAll(refreshToken,userInfo);
            redisTemplate.expire(refreshToken,JWTUtils.REFRESH_TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
            return chain.filter(exchange);
        }
    }
    @Override
    public int getOrder() {
        //最高优先级的过滤器，数值越小优先级越高
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
